// Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
// This source file is part of the Cangjie project, licensed under Apache-2.0
// with Runtime Library Exception.
//
// See https://cangjie-lang.cn/pages/LICENSE for license information.

#include <iostream>

#include "Platform/Export.h"

#include "Interfaces.h"

#include "Option.h"
#include "Config.h"
#include "TomlFile.h"
#include "Migrators/Migrator.h"
#include "Rules/RuleList.h"

using namespace CangjieMigrator;

EXPORT const char *UpdaterGetVersion()
{
    return BASE_VERSION;
}

EXPORT ApplyReturnCode UpdaterApply(const UpdaterOption *inputOption)
{
    auto option = Option(*inputOption);

    auto toml = TomlFile();
    {
        const auto tomlPath = Config::BinDependencyDir / "rules";
        (void)toml.ReadDirectory(tomlPath);
        if (toml.IsEmpty()) {
            std::cerr << "Failed to read config path: " << tomlPath << std::endl;
            return 1;
        }
    }

    auto rules = std::make_unique<Rules::RuleList>(toml);
    if (rules->IsEmpty()) {
        std::cerr << "Failed to read rules. " << std::endl;
        return 1;
    }

    auto migrator = Migrator::Create(inputOption->cangjieHome, option, BASE_VERSION, std::move(rules));
    bool success = migrator->Convert();
    if (!success) {
        std::cerr << "Failed to perform update on Version " << migrator->GetVersion() << std::endl;
        return 1;
    }
    std::cout << "Finish conversion on Version " << migrator->GetVersion() << std::endl;
    return 0;
}
